package com.huawei.aiservice.filters;

import com.huawei.aiservice.base.Login;
import com.huawei.aiservice.base.LoginFactory;
import com.huawei.aiservice.constants.GatewayConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class UrlFilter implements GlobalFilter, Ordered {
    @Autowired
    private LoginFactory loginFactory;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.equals("/api/login")) {
            return toLogin(request, response);
        }

        // 登录验证
        if ("/api/validate/login/gitee".equals(path)) {
            return auth(request, response);
        }

        return chain.filter(exchange);
    }

    /**
     * 登录-验证
     *
     * @param request 请求
     * @param response 响应
     * @return 返回信息
     */
    public Mono<Void> auth(ServerHttpRequest request, ServerHttpResponse response) {
        String type = null;
        if (request.getURI().getPath().equals("/api/validate/login/hw")) {
            type = GatewayConstant.AuthType.HW;
        }
        if (request.getURI().getPath().equals("/api/validate/login/gitee")) {
            type = GatewayConstant.AuthType.GITEE;
        }
        if (type != null) {
            Login login = loginFactory.createLogin(type);
            return login.auth(request, response);
        }
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        return response.setComplete();
    }

    /**
     * 跳转到码云授权登录页
     *
     * @param request 请求
     * @param response 响应
     * @return 返回信息
     */
    public Mono<Void> toLogin(ServerHttpRequest request, ServerHttpResponse response) {
        String type = request.getQueryParams().getFirst("type");
        if (StringUtils.isBlank(type)) {
            type = GatewayConstant.AuthType.GITEE;
        }
        Login login = loginFactory.createLogin(type);
        return login.toLogin(request, response);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
